<template>
    <div class="seckillall">
        <div class="head">
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="栏目名称" prop="courseName">
                    <el-input v-model="queryParams.courseName" placeholder="请输入课程名称" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="栏目状态" prop="courseStatus">
                    <!-- <el-input v-model="queryParams.courseStatus" placeholder="请输入栏目状态" clearable
                        style="width: 240px" /> -->
                    <el-select v-model="queryParams.courseStatus" placeholder="请选择课程状态" filterable>
                        <el-option label="启用" value="0"></el-option>
                        <el-option label="禁用" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="老师名称" prop="teacherId">
                    <el-select v-model="queryParams.teacherId" placeholder="请选择教师" filterable>
                        <el-option v-for="item in teacherList" :label="item.teacherName" :key="item.teacherId"
                            :value="item.teacherId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程栏目"  prop="categoryId">
                    <!-- <el-input v-model="formData.categoryId" autocomplete="off"></el-input> -->
                    <el-select v-model="queryParams.categoryId" placeholder="请选择课程栏目" 
                         filterable >
                        <el-option v-for="item in categoryList" :label="item.categoryName" :key="item.categoryId"
                            :value="item.categoryId"></el-option>
                    </el-select>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" size="default" @click="searchBtn()">搜索</el-button>
                    <el-button size="default" @click="resetBtn">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="middle">
                <div class="add" style="margin-left: 20px;">
                    <div class="button">
                        <el-button type="primary" :icon="Plus" @click="handleAdd()" plain>新增</el-button>
                    </div>
                </div>
                <div class=" add">
                    <div class="button">
                        <el-button type="success" :icon="Edit" @click="handleEdit()" :disabled="single"
                            plain>修改</el-button>
                    </div>
                </div>
                <div class=" add">
                    <div class="button">
                        <el-button type="danger" :icon="Delete" @click="handleDelete()" :disabled="multiple" plain>
                            删除
                        </el-button>
                    </div>
                </div>


            </div>
            <div class="end">
                <el-table :data="tableData" row-key="courseId" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" />
                    <el-table-column label="序号" prop="index">
                        <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column property="courseName" label="栏目名称" />

                    <el-table-column property="coursePrice" label="课程价格" />
                    <el-table-column property="courseStock" label="库存数" />

                    <el-table-column property="categoryName" label="栏目名称" />
                    <el-table-column property="teacherName" label="老师名称" />

                    <el-table-column property="courseStart" label="开始时间" />
                    <el-table-column property="courseEnd" label="结束时间" />
                    <el-table-column property="courseRemark" label="课程备注" />
                    <el-table-column label="状态">
                        <template #default="scope">
                            <!-- {{ scope.row.courseStatus }} -->
                            <el-button type="success" v-if="scope.row.courseStatus == 0" plain>启用</el-button>
                            <el-button type="warning" v-else plain>禁用</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" @click="handleEdit(scope.row)">
                                修改
                            </el-button>
                            <br>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-left: 600px;">
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="queryParams.pageNum"
                            v-model:page-size="queryParams.pageSize" :page-sizes="[1, 2, 20, 50]"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>

            </div>

            <el-dialog v-model="dialogVisible" :modal="true" width="800px">

                <el-form :model="formData" :rules="rules" ref="categoryForm">
                    <el-row>

                        <el-col :span="11">
                            <el-form-item label="课程名称" label-width="120px" prop="courseName">
                                <el-input v-model="formData.courseName" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>

                        <!-- <el-col :span="11">
                            <el-form-item label="课程" label-width="120px" prop="courseId">
                                <el-select v-model="formData.courseId" placeholder="请选择课程" label-width="120"
                                    @change="handleCourseSelect" filterable required :disabled="disabled">
                                    <el-option v-for="item in courseList" :label="item.courseName" :key="item.value"
                                        :value="item.courseId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="11">
                            <el-form-item label="课程库存" label-width="120px" prop="courseStock">
                                <el-input v-model="formData.courseStock" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="课程价格" label-width="120px" prop="coursePrice">
                                <el-input v-model="formData.coursePrice" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="课程老师" label-width="120px" prop="teacherId">
                                <!-- <el-input v-model="formData.teacherId" autocomplete="off"></el-input> -->
                                <el-select v-model="formData.teacherId" placeholder="请选择教师" label-width="120"
                                   filterable required :disabled="disabled">
                                    <el-option v-for="item in teacherList" :label="item.teacherName"
                                        :key="item.teacherId" :value="item.teacherId"></el-option>
                                </el-select>

                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="开始时间" label-width="120px" prop="courseStart">
                                <!-- <el-input v-model="formData.courseStart" autocomplete="off"></el-input> -->
                                <div class="block">
                                    <el-date-picker v-model="formData.courseStart" type="date"
                                        value-format="YYYY-MM-DD HH:mm" format="YYYY-MM-DD HH:mm" placeholder="选择日期">
                                    </el-date-picker>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="持续时间(周)" label-width="120px" prop="courseTime">
                                <el-input-number v-model="formData.courseTime" :min="1" :max="72" />
                                <!-- <el-input v-model="formData.courseTime" autocomplete="off"></el-input> -->
                            </el-form-item>
                        </el-col>

                    </el-row>

                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="课程栏目" label-width="120px" prop="categoryId">
                                <!-- <el-input v-model="formData.categoryId" autocomplete="off"></el-input> -->
                                <el-select v-model="formData.categoryId" placeholder="请选择课程栏目" label-width="120"
                                   filterable required :disabled="disabled">
                                    <el-option v-for="item in categoryList" :label="item.categoryName"
                                        :key="item.categoryId" :value="item.categoryId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="图片路径" label-width="120px" prop="imagePath">
                                <el-input v-model="formData.imagePath" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>

                        <el-col :span="22">
                            <el-form-item label="课程备注" label-width="120px" prop="courseRemark">
                                <el-input v-model="formData.courseRemark" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>



                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleCanle">取消</el-button>
                        <el-button type="primary" @click="handleConfirm">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>

            <el-dialog v-model="deleteDialog" title="Tips" width="500">
                <span>确认要删除吗？</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="deleteDialog = false">取消</el-button>
                        <el-button type="primary" @click="deleteConfirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>

        </div>
    </div>
</template>
a
<script setup>
import { ref, onMounted } from 'vue'
import { Calendar, Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { selectAllCourse, selectAllTeacher, selectAllCategory, addCourse, getCourse, updateCourse, deleteCourse } from '@/api/course'


//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true)
const multiple = ref(true)
const total = ref(10);
const dialogVisible = ref(false)

const selected = ref("add");
//是否禁用表单
const disabled = ref(false)
const selectRow = ref([]);
const deleteDialog = ref(false)
const deleteRow = ref([])
const teacherList = ref([])
const categoryList = ref([])

onMounted(async () => {
    await getTeacherList();
    await getAllCategory();
    await getCourseList();

})
//查询参数
const queryParams = ref({
    courseId: '',
    courseName: '',
    courseStatus: '',

    pageNum: 1,
    pageSize: 2,

    categoryId: '',
    teacherId: '',

})
// 表单参数
var formData = ref({
    courseId: '',
    courseName: '',
    categoryId: '',
    teacherId: '',
    courseStock: '',
    coursePrice: '',
    courseRemark: '',
    courseStart: '',
    courseTime: 1,
})
//表格参数
const tableData = ref([])
//校验规则
const rules = {
    courseName: [
        { required: true, message: '请输入课程名称', trigger: 'blur' }
    ],
    courseStock: [
        { required: true, message: '请输入课程库存', trigger: 'blur' },
        {
            type: 'number',
            message: '库存必须为数字值',
            transform: value => Number(value)
        },
        {
            validator: (rule, value) => value >= 0,
            message: '库存不能为负数',
            trigger: 'blur'
        }
    ],
    coursePrice: [
        { required: true, message: '请输入课程价格', trigger: 'blur' },
        {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '请输入有效的价格格式（最多两位小数）',
            trigger: 'blur'
        }
    ],
    teacherId: [
        { required: true, message: '请选择授课教师', trigger: 'change' }
    ],
    categoryId: [
        { required: true, message: '请选择课程栏目', trigger: 'change' }
    ],
    courseStart: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    courseTime: [
        {
            type: 'number',
            min: 1,
            max: 72,
            message: '持续时间需在1-72周之间',
            trigger: 'blur'
        }
    ],
    imagePath: [
        { required: true, message: '请输入图片路径', trigger: 'blur' },
        {
            pattern: /\.(jpg|jpeg|png|gif|webp)$/,
            message: '请输入有效的图片文件路径',
            trigger: 'blur'
        }
    ]
};
// 修改
function handleEdit(row) {
    resetForm();
    if (row == null) {
        row = selectRow.value[0];
    }
    console.log(row, 123)
    // console.log(row.courseId)
    disabled.value = true
    selected.value = 'edit'
    const data = {
        courseId: row.courseId
    }
    getCourse(data).then(res => {
        formData.value = res.data.course;
        dialogVisible.value = true
    })

}
// 删除
function handleDelete(row) {
    if (row == null) {
        row = selectRow.value.map(item => {
            return item.courseId
        })
    } else {
        console.log(row)
        row = [row.courseId]
    }
    deleteRow.value = row
    deleteDialog.value = true;



}
//删除确定
function deleteConfirm() {

    deleteCourse(deleteRow.value).then(res => {
        if (res.code === 500) {
            ElMessage.error(res.message);
        } else {
            ElMessage.success("删除成功")

        }
        getCourseList();
    })
    deleteDialog.value = false;

}

//新增
function handleAdd() {
    dialogVisible.value = true
    selected.value = 'add'
    resetForm();
}
//每页条数变换
function handleSizeChange(val) {
    console.log("每页" + val + "条");
    queryParams.value.pageSize = val;
    queryParams.value.pageNum = 1;
    getCourseList();


}
//每码变换
function handleCurrentChange(val) {
    console.log("第" + val + "页")
    queryParams.value.pageNum = val;
    getCourseList();
}

//关闭dialog
function handleCanle() {
    dialogVisible.value = false
    // 重置表单字段
    categoryForm.value.resetFields();

    // 清除表单验证
    categoryForm.value.clearValidate();

}

// 选中某一列
function handleSelectionChange(selected) {
    console.log(selected, selected.length)
    single.value = selected.length != 1
    multiple.value = selected.length == 0
    selectRow.value = selected;

}

function handleConfirm() {
    // 验证表单 xxx
    categoryForm.value.validate((valid) => {
        // 重置表单字段
        // categoryForm.value.resetFields();
        if (valid) {
            // 表单验证通过，执行提交操作
            if (selected.value === 'add') {
                console.log(formData.value, 99);
                addCourse(formData.value).then(res => {
                    console.log(res);
                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("新增成功")
                    }
                    getCourseList();
                    dialogVisible.value = false
                })

            } else {
                updateCourse(formData.value).then(res => {
                    console.log(res);
                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("修改成功")
                    }
                    getCourseList();
                    dialogVisible.value = false
                })
            }
        } else {
            // 表单验证失败，显示错误信息
            ElMessage.warning("请填写完整")
        }
    });


    // 清除表单验证
    categoryForm.value.clearValidate();

}

function searchBtn() {
    queryParams.value.pageNum = 1;
    getCourseList()
}

function resetBtn() {
    queryParams.value = {
        courseId: '',
        courseName: '',
        pageNum: 1,
        courseStatus: '',
        pageSize: queryParams.value.pageSize,
    }
    getCourseList()
}

function resetForm() {
    formData.value = {
        courseId: '',
        courseName: '',
    }
    disabled.value = false
    selected.value = 'add'
}


async function getCourseList() {
    // selectAllCourse(queryParams.value).then(res => {
    //     console.log(res, 123)
    //     total.value = res.data.list.total
    //     tableData.value = res.data.list.records
    // })
    try {
        const res = await selectAllCourse(queryParams.value);
        total.value = res.data.list.total
        tableData.value = res.data.list.records
        for (const item of tableData.value) {
            for (const element of teacherList.value) {
                if (element.teacherId == item.teacherId) {
                    item.teacherName = element.teacherName
                }
            }
            for (const element of categoryList.value) {
                if (element.categoryId == item.categoryId) {
                    item.categoryName = element.categoryName
                }
            }
        }
    } catch (error) {
        console.log(error)
    }

}

async function getTeacherList() {
    try {
        const res = await selectAllTeacher();
        teacherList.value = res.data.teacherList
        console.log(teacherList.value)
    } catch (e) {
        console.log(e)
    }

}

async function getAllCategory() {
    try {
        const res = await selectAllCategory();
        categoryList.value = res.data.categoryList
        console.log(categoryList.value)
    } catch {
        console.log(e)
    }

}




</script>

<style scoped>
.seckillall {
    height: 100%;
    width: calc(100% - 50px);
    /* background-color: pink; */
    float: left;
}

.head {
    margin-top: 20px;
    margin-left: 20px;
    width: calc(100% - 50px);
}

.middle {
    width: 100%;
    height: 8vh;
    /* background-color: antiquewhite; */
    margin-bottom: 20px;
}

.add {
    margin-top: 15px;
    margin-left: 45px;
    width: 5%;
    height: 50%;
    float: left;
}

.end {
    float: left;
    width: calc(100% - 50px);
}
</style>